"""
This part of code is the Q learning brain, which is a brain of the agent.
All decisions are made in here.

Reference: https://morvanzhou.github.io/tutorials/
"""

import numpy as np
import pandas as pd


class RL(object): # 父类
    def __init__(self, action_space, learning_rate=0.01, reward_decay=0.9, e_greedy=0.9):
        self.actions = action_space  # a list 动作空间
        self.lr = learning_rate # 学习率
        self.gamma = reward_decay # 衰减率
        self.epsilon = e_greedy # 贪婪度

        self.q_table = pd.DataFrame(columns=self.actions, dtype=np.float64)

    def check_state_exist(self, state):
        if state not in self.q_table.index:
            # append new state to q table
            self.q_table = pd.concat([
                self.q_table,
                pd.DataFrame(
                    [[0] * len(self.actions)],
                    columns=self.q_table.columns,
                    index=[state]
                )
            ])
    '''
    #append方法废止
    def check_state_exist(self, state): # 检查状态是否存在
        if state not in self.q_table.index:
            # append new state to q table
            self.q_table = self.q_table.append(
                pd.Series(
                    [0]*len(self.actions),
                    index=self.q_table.columns,
                    name=state,
                )
            )
    '''

    def choose_action(self, observation): # 选择动作
        self.check_state_exist(observation)
        # action selection
        if np.random.rand() < self.epsilon:
            # choose best action
            state_action = self.q_table.loc[observation, :]
            # some actions may have the same value, randomly choose on in these actions 
            action = np.random.choice(state_action[state_action == np.max(state_action)].index) # 随机选择动作
        else:
            # choose random action
            action = np.random.choice(self.actions) # 随机选择动作
        return action

    def learn(self, *args): 
        #抽象方法，需要在子类中实现，根据当前状态、动作、奖励、下一个状态进行学习
        pass #pass 表示不做任何事情，只是占位符


# off-policy 离线策略 Q-learning algorithm
class QLearningTable(RL):
    def __init__(self, actions, learning_rate=0.01, reward_decay=0.9, e_greedy=0.9):
        super(QLearningTable, self).__init__(actions, learning_rate, reward_decay, e_greedy) 
        # 继承父类，super() 函数是用于调用父类(超类)的一个方法。

    def learn(self, s, a, r, s_):
        self.check_state_exist(s_)
        q_predict = self.q_table.loc[s, a]
        if s_ != 'terminal':
            q_target = r + self.gamma * self.q_table.loc[s_, :].max()  # next state is not terminal
        else:
            q_target = r  # next state is terminal
        self.q_table.loc[s, a] += self.lr * (q_target - q_predict)  # update


# on-policy 在线策略 SARSA algorithm 
# 主要区别在Q值的更新方式
class SarsaTable(RL):

    def __init__(self, actions, learning_rate=0.01, reward_decay=0.9, e_greedy=0.9):
        super(SarsaTable, self).__init__(actions, learning_rate, reward_decay, e_greedy)

    def learn(self, s, a, r, s_, a_):
        self.check_state_exist(s_)
        q_predict = self.q_table.loc[s, a]
        if s_ != 'terminal':
            q_target = r + self.gamma * self.q_table.loc[s_, a_]  # next state is not terminal
        else:
            q_target = r  # next state is terminal
        self.q_table.loc[s, a] += self.lr * (q_target - q_predict)  # update
